package paper.xml;

import java.io.*;
import java.util.*;

class SurroundStream extends InputStream
{
    static final int PREFIX=0,FILE=1,POSTFIX=2;
    BufferedInputStream real;
    int pos,state;
    static final String prefix = "<root>",postfix = "</root>";
    SurroundStream(File file) throws FileNotFoundException
    {
        real = new BufferedInputStream(new FileInputStream(file));
        pos = 0;
        state = PREFIX;
    }
    public int read(char[] b) throws IOException
    {
        int left = b.length,outpos=0;
        int c;
        byte[] copy = new byte[left];
        switch(state)
        {
            case PREFIX:
                if( prefix.length()-pos > left )
                {
                    System.arraycopy(prefix,pos,b,0,left);
                    pos += left;
                    return left;
                }
                System.arraycopy(prefix,pos,b,0,prefix.length()-pos);
                state = FILE;
                left -= prefix.length()-pos;
                outpos = prefix.length()-pos;
            case FILE:
                c = 0;
                while( outpos+c < left &&
                       c != -1)
                {
                    c = real.read(copy,0,left);
                    String temp = new String(copy,0,c);
                    temp.getChars(0,left-1,b,outpos);
                    if( c == -1 && c==left)
                        return outpos+c;
                    outpos += c;
                    left -= c;
                }
                if( left==0 )
                    return outpos;
                pos = 0;
                state = POSTFIX;
            case POSTFIX:
                if( pos == postfix.length() )
                    return -1;
                if( postfix.length()-pos > left )
                {
                    System.arraycopy(postfix,pos,b,0,left);
                    pos += left;
                    return left;
                }
                System.arraycopy(postfix,pos,b,outpos,postfix.length()-pos);
                int copied = postfix.length()-pos;
                pos = postfix.length();
                return copied;
        }
        return -1;      // JAVA STATIC ANALYSIS SUCKS HIPPO COCK
    }

    public int read() throws IOException
    {
        int c;
        switch(state)
        {
            case PREFIX:
                if( pos < prefix.length() )
                    return (int)prefix.charAt(pos++);
                state = FILE;
            case FILE:
                c = real.read();
                if( c != -1 )
                    return c;
                pos = 0;
                state = POSTFIX;
            case POSTFIX:
                if( pos < postfix.length() )
                    return (int)postfix.charAt(pos++);
                return -1;
        }
        return -1;      // JAVA STATIC ANALYSIS SUCKS HIPPO COCK
    }
}
